<template>
  <div class="face">
    <Header></Header>
    <div class="body">
      <!-- <el-upload
        class="avatar-uploader"
        action="http://localhost:8080/api/my/userfacelogin"
        :show-file-list="false"
        :on-success="handleAvatarSuccess"
      >
        <img v-if="imageUrl" :src="imageUrl" class="avatar" />
        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
      </el-upload>
      <span>拍照或者上传图片</span> -->
      <van-uploader
        v-model="fileList"
        :after-read="afterRead"
        preview-size="120px"
        :max-count="1"
      />
      <span>人脸登录</span>
    </div>
  </div>
</template>

<script>
import Header from "@/views/Login/Header"
import { Toast } from "vant"
import { mapState, mapGetters, mapMutations, mapActions } from "vuex"
import ImageCompressor from "js-image-compressor"
export default {
  components: {
    Header,
  },
  data() {
    return {
      imageUrl: "",
      fileList: [],
      dataBase: "",
    }
  },
  methods: {
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
      console.log(res)
      let data = JSON.parse(res.data)
      console.log(data)
      let [isMate] = data.result.user_list
      console.log(isMate)
      let userIsMate = isMate.score
      if (userIsMate < 80) {
        Toast("人脸登录失败")
      } else {
        Toast("人脸登录成功")
        // 用户登录接口
        let params = { phone: isMate.user_id }
        this.$api.user.login(params).then((res) => {
          console.log(res)
          this.status = res.status
          // 账号未注册
          if (this.status == 405) {
            Toast("账号未注册")
            return
          } else {
            this.userLogin(res)
            this.$router.push("/my")
          }
        })
      }
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg"
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!")
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!")
      }
      return isJPG && isLt2M
    },

    afterRead(file) {
      console.log(file)
      let files = file.file
      let self = this
      // 使用promise接受处理结果
      return new Promise((resolve, reject) => {
        new ImageCompressor({
          // 图片压缩配置
          file: files,
          quality: 0.6,
          mimeType: "image/jpeg",
          maxWidth: 2000,
          maxHeight: 2000,
          width: 1000,
          height: 1000,
          minWidth: 500,
          minHeight: 500,
          convertSize: Infinity,
          loose: true,
          redressOrientation: true,
          // 压缩前回调
          beforeCompress: function (result) {
            console.log("压缩之前图片尺寸大小: ", result.size)
            console.log("mime 类型: ", result.type)
          },
          // 压缩成功回调
          success: function (result) {
            console.log("压缩结果:", result)
            console.log("压缩之后图片尺寸大小: ", result.size)
            console.log("mime 类型: ", result.type)
            console.log(
              "实际压缩率： ",
              (((this.file.size - result.size) / this.file.size) * 100).toFixed(
                2
              ) + "%"
            )

            resolve(result)
          },
          // 发生错误
          error: function (msg) {
            reject(msg)
            console.error(msg)
          },
        })
      }).then((res) => {
        console.log(res)
        let blob = res
        let reader = new FileReader()
        reader.readAsDataURL(blob)
        reader.onloadend = function () {
          let base64data = reader.result
          console.log(base64data)
          self.dataBase = base64data.split(",")[1]
          let params = { value: self.dataBase }
          console.log(params)

          file.status = "uploading"
          file.message = "识别中..."
          // 将base64编码发送到后端
          self.$api.my.userFaceLogin(params).then((res) => {
            console.log(res)
            let data = JSON.parse(res.data)
            console.log(data)
            if (!data.result) {
              Toast(data.error_msg)
              file.status = "failed"
              file.message = "识别失败"
            } else {
              let [isMate] = data.result.user_list
              console.log(isMate)
              let userIsMate = isMate.score
              if (userIsMate < 80) {
                Toast("人脸登录失败")
              } else {
                Toast("人脸登录成功")
                // 用户登录接口
                let params = { phone: isMate.user_id }
                self.$api.user.login(params).then((res) => {
                  console.log(res)
                  self.status = res.status
                  // 账号未注册
                  if (self.status == 405) {
                    Toast("账号未注册")
                    return
                  } else {
                    self.userLogin(res)
                    self.$router.push("/my")
                  }
                })
              }
            }
          })
        }
        // let dataBase = file.content.split(",")[1]
      })
      let params = { value: self.dataBase }
      console.log(params)
      console.log(dataBase)
      file.status = "uploading"
      file.message = "识别中..."
      // 将base64编码发送到后端
      self.$api.my.userFaceLogin(params).then((res) => {
        console.log(res)
        let data = JSON.parse(res.data)
        console.log(data)
        let [isMate] = data.result.user_list
        console.log(isMate)
        let userIsMate = isMate.score
        if (userIsMate < 80) {
          Toast("人脸登录失败")
        } else {
          Toast("人脸登录成功")
          // 用户登录接口
          let params = { phone: isMate.user_id }
          self.$api.user.login(params).then((res) => {
            console.log(res)
            self.status = res.status
            // 账号未注册
            if (self.status == 405) {
              Toast("账号未注册")
              return
            } else {
              self.userLogin(res)
              self.$router.push("/my")
            }
          })
        }
      })
    },

    ...mapMutations(["userLogin"]),
  },
}
</script>

<style lang="less" scoped>
.face {
  width: 100vw;
  height: 100vh;
}

.upload {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 200px;
  height: 200px /* 200/80 */;
  background-color: rgb(241, 243, 244);
  border-radius: 50%;
}

.body {
  width: 100vw;
  height: 300px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

span {
  margin: 10px;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;

  // background-color: rgb(222, 225, 230);
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
  background-color: rgb(222, 225, 223);
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.preview-cover {
  position: absolute;
  bottom: 0;
  box-sizing: border-box;
  width: 100%;
  padding: 4px;
  color: #fff;
  font-size: 12px;
  text-align: center;
  background: rgba(0, 0, 0, 0.3);
}
</style>
